package com.sumainfor.pc.gmio.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.DateUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.Jsapi_ticketUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.common.wechat.WeChatConfig;
import com.sumainfor.pc.gmio.dao.TemporaryBillMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Meng
 * @ClassName TemporaryBillService
 * @date 2020/1/3 16:17
 * @description: TODO
 */
@Service
public class TemporaryBillService {


    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(TemporaryBillService.class);

    @Autowired
    TemporaryBillMapper temporaryBillMapper;

    @Autowired
    UtilsMapper utilsMapper;

    /**
     * 增加临时账单
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addBillTem(Map<String,Object> params){

        JsonResult result = new JsonResult();

        lock.lock();
        try {
            //获取当前时间
            Date nowTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String GenerateTimeNow = sdf.format(nowTime);//租赁顾问签约抄水电燃,抄表记录的时间默认一致,

            String  BiIdUUID = "";//临时账单编号
            //获取账单编号
            Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                put("uuid", "BiId");
                put("database", Constants.DATA_SOURCE_GMIO);
                put("surface", "tcgmio_tenant_bill");
            }});
            if(BiIduuid!=null){
                int number=Integer.valueOf(BiIduuid.get("uuid").toString());
                BiIdUUID= ComUtils.getLocalTrmSeqNum("BILS",number);

            }else{
                BiIdUUID=ComUtils.getLocalTrmSeqNum("BILS",0);
            }

            params.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
            params.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(params);
            params.put("BiId",BiIdUUID);//账单编号
            //params.put("CorId",map3.get("CorId"));//账单归属公司//
            params.put("BiName","临时账单"+params.get("BiName").toString());//账单名称
            params.put("IfTemporary",1);//是否是临时账单0否 1 是
            params.put("BiType",4);//账单类型 临时账单
            //params.put("Source",WatUUID);//账单来源
            //params.put("PubType",1);//公共事业费类型1水费
            //params.put("BiMoney",beforePooled);//账单金额,每个租客本次抄表需支付金额
            params.put("BillExplain","临时账单");//账单金额说明
            // billMap.put("BiGenerated",GenerateTimeNow);//账单生成日
            // billMap.put("EndTime",DateUtils.addDateDays(date,15));//账单结束日
            params.put("LateDay",params.get("BiGenerated"));//账单开始日
           // params.put("TenId",map3.get("TenId"));//租客编号
           // params.put("HouId",map3.get("HouId"));//房源编号
           // params.put("HouInfoId",map3.get("HouInfoId"));//房源详表编号
            params.put("CreateType",2);//账单创建人类型1系统 2 人为
            params.put("Create",ContextUtils.getUserId());//账单创建人
            params.put("ExpTime",params.get("LateDay"));//逾期开始时间
            params.put("Status",1);//1待支付

            Integer cout = temporaryBillMapper.addBillTem(params);
            if (cout>0){
                result.putSuccess("新增临时账单成功");
                //推送模板
                //推送微信模板
                String touser=params.get("uopid").toString();//租客的openid
                Map<String, TemplateData> param = new HashMap<>();
                param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的"+params.get("Realname").toString()+"租客，您本期账单已出。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                param.put("keyword1", new TemplateData(params.get("BiGenerated").toString()+"-"+params.get("EndTime"), "#4876FF"));//账单周期
                param.put("keyword2", new TemplateData(params.get("BiMoney").toString(), "#4876FF"));//账单金额
                param.put("keyword3", new TemplateData(params.get("LateDay").toString(), "#4876FF"));//最晚缴费日期
                Jsapi_ticketUtil.sendTemplate(touser, "kYdIsyu8tuBtDAWTgQ-Fl2rcbfFYq7g8_fTn9o55sRU","http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));

            }else{
                return result.putFailed("新增临时账单失败");

            }



        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
        } finally {
            lock.unlock();
        }

        return result;

    }


}
